<?php

namespace app\Modules\Api\controllers;



use Yii;
use app\models\Pic;
use app\models\BidQueue;
use app\models\BidSericesqueue;
use app\Modules\Api\models\BidRcd;
use app\Modules\Api\models\User;
use app\Modules\Api\models\Auction;
use app\Modules\Api\models\Product;
use app\Modules\Api\models\Saleorder;
use app\Modules\Api\models\Showorder;
use app\Modules\Api\models\Showpic;
use app\Modules\Api\models\Bill;
use app\Modules\Api\helper\Pagination;
use yii\helpers\ArrayHelper;
use app\filters\Json;
use app\helpers\Request;
use yii\helpers\Url;

/**
 * Class ProductController
 * @package app\Modules\Api\controllers
 */
class AuctionController extends ControllerBase
{
    /**
     * 商品详情
     * @return array
     */
    public function actionIndex()
    {
        $product_id = Request::strictpost('product_id','缺少产品id');
        $user_id = Yii::$app->request->post('user_id',0);
        $auction_id = Yii::$app->request->post('auction_id',0);
        $product_object = Product::findOne($product_id);
        if(!$product_object)
            return Json::error('商品已下架');

        $fields = ['pid','name','type_id','spec'];
        $product = $product_object->toArray($fields);
        //图片
        $product['pics'] = ArrayHelper::getColumn(Pic::find()->where(['product_id'=>$product_id])->orderBy(['created_at'=>SORT_DESC])->all(),function($element){
            return Yii::$app->params['uploadUrl'].$element['url'];
        });
        //当前竞拍参数
        $this_auction_object = Auction::getFirst($product_id);
        $first_auction_object = $auction_id?Auction::findOne($auction_id):$this_auction_object;
        $first_auction = $first_auction_object
            ->toArray([
                'actcount',
                'reacount',
                'price',
                'start_price',
                'scope',
                'fee',
                'market_val',
                'return_rate',
            ],['auction_state']);
        $product = array_merge($product,$first_auction);
        //竞拍记录
        $auction_objects = Auction::find()->where(['product_id'=>$product_id,'state'=>Auction::STATE_NOT_AUCTION])->orderBy(['created_at'=>SORT_DESC])->limit(5)->all();
        $auctions = [];
        foreach($auction_objects as $auction_object){
            $auctions[] = $auction_object->toArray(['nickname','market_val','price','end_at'],['uimg','cut']);
        }
        $product['auctions'] = $auctions;
        //出价记录
        $bid_rcd_query = BidRcd::find()->where(['auction_id'=>$first_auction_object->auctionid])->orderBy(['bidrcdid'=>SORT_DESC]);
        $bid_rcds = $bid_rcd_query->limit(3)->all();
        $product['top']= $bid_rcds?$bid_rcds[0]->toArray(['price','name']):new \stdClass();
        $product['bid_rcds'] = $bid_rcds;
        $product['auction_id'] = strval($first_auction_object->auctionid);
        $product['next_auction_id'] = strval($this_auction_object->auctionid);
        $product['bid_rcd_count'] = strval($bid_rcd_query->count());
        //消费
        $user = User::findOne($user_id);
        if(!$user){
            $product['use_take_money'] = strval(0);
            $product['use_give_money'] = strval(0);
        }else{
            $order = Saleorder::getOrCreate($first_auction_object,$user);
            $product['use_take_money'] = strval($order->take_money);
            $product['use_give_money'] = strval($order->give_money);
        }
        //晒单
        /** @var  $showorder_objects Showpic*/
        $showorder_objects = Showorder::find()->where(['product_id'=>$product_id])->limit(20)->all();
        $showorders = [];
        foreach($showorder_objects as $key =>$showorder_object)
        {
            $showorders[$key] = $showorder_object->toArray([],['showpics']);
        }
        $product['rcd_url'] = Yii::$app->params['baseUrlnotend'].Url::to(['historyjson','product_id'=>$product_id]);
        $product['showorders'] = $showorders;
        //竞拍规则
        $product['rule'] = [
            'aaa','bbb','ccc'
        ];
        //连续拍
        /** @var  $bid_sericesque BidSericesqueue*/
        $bid_sericesque = BidSericesqueue::find()->where(['auction_id'=>$first_auction_object->auctionid,'user_id'=>$user_id])->one();
        if($bid_sericesque){
            $product['bid_num'] = strval($bid_sericesque->initial_num-$bid_sericesque->num);
            $product['bid_initial_num'] = strval($bid_sericesque->initial_num);
        }else{
            $product['bid_num'] = '0';
            $product['bid_initial_num'] = '0';
        }
        $data = $product;
        return Json::success($data);
    }
    /**
     * 往期竞拍（详情）
     * @return array
     */
    public function actionAll(){
        $product_id = Request::strictpost('product_id','缺少产品id');
        $query = Auction::find()->where(['product_id'=>$product_id,'state'=>Auction::STATE_NOT_AUCTION]);
        $count = $query->count();
        $pagination = Pagination::get($count);
        $objects = $query
            ->orderBy(['created_at'=>SORT_DESC])
            ->limit($pagination->limit)
            ->offset($pagination->offset)
            ->all();
        $auctions = [];
        foreach($objects as $object){
            $auctions[] = $object->toArray(['nickname','market_val','price','end_at'],['uimg','cut']);
        }
        $data = [
            'auctions'=>$auctions,
            'auction_count'=>$count,
        ];
        return Json::success($data);
    }
    /**
     * 竞拍内容
     * @return array
     */
    public function actionDetail(){
        $product_id = Request::strictpost('product_id','缺少产品id');
        $user_id = Yii::$app->request->post('user_id',0);
        $auction_id = Yii::$app->request->post('auction_id',0);
        $product_object = Product::findOne($product_id);
        if(!$product_object)
            return Json::error('商品已下架');

        $fields = ['pid'];
        $product = $product_object->toArray($fields);
        //当前竞拍参数
        $this_auction_object = Auction::getFirst($product_id);
        $first_auction_object = $auction_id?Auction::findOne($auction_id):$this_auction_object;
        $first_auction = $first_auction_object
            ->toArray([
                'actcount',
                'reacount',
                'price',
            ],['auction_state']);
        $product = array_merge($product,$first_auction);
        //出价记录
        $bid_rcd_query = BidRcd::find()->where(['auction_id'=>$first_auction_object->auctionid])->orderBy(['bidrcdid'=>SORT_DESC]);
        $bid_rcds = $bid_rcd_query->limit(3)->all();
        $product['top']= $bid_rcds?$bid_rcds[0]->toArray(['price','name']):new \stdClass();
        $product['bid_rcds'] = $bid_rcds;
        $product['auction_id'] = strval($first_auction_object->auctionid);
        $product['next_auction_id'] = strval($this_auction_object->auctionid);
        $product['bid_rcd_count'] = strval($bid_rcd_query->count());
        //消费
        $user = User::findOne($user_id);
        if(!$user){
            $product['use_take_money'] = strval(0);
            $product['use_give_money'] = strval(0);
        }else{
            $order = Saleorder::getOrCreate($first_auction_object,$user);
            $product['use_take_money'] = strval($order->take_money);
            $product['use_give_money'] = strval($order->give_money);
        }
        //连续拍
        /** @var  $bid_sericesque BidSericesqueue*/
        $bid_sericesque = BidSericesqueue::find()->where(['auction_id'=>$first_auction_object->auctionid,'user_id'=>$user_id])->one();
        if($bid_sericesque){
            $product['bid_num'] = strval($bid_sericesque->initial_num-$bid_sericesque->num);
            $product['bid_initial_num'] = strval($bid_sericesque->initial_num);
        }else{
            $product['bid_num'] = '0';
            $product['bid_initial_num'] = '0';
        }
        $data = $product;
        return Json::success($data);
    }

    /**
     * 出价
     * @return array
     */
    public function actionUse()
    {
        $product_id = Request::strictpost('product_id','缺少产品id');
        $user_id = Request::strictpost('user_id','缺少用户id');
        $strict = Yii::$app->request->post('strict',0);
        $product = Product::findOne($product_id);
        if(!$product)
            return Json::error('产品不存在');
        $auction = Auction::getFirst($product_id);
        if($auction->state !== Auction::STATE_IS_AUCTION)
            return Json::error('产品未在竞拍中');
        $user = User::findOne($user_id);
        if(!$user)
            return Json::error('用户不存在');
        /** @var  $topRcd BidRcd*/
        $topRcd = BidRcd::find()->where(['auction_id'=>$auction->auctionid])->orderBy(['price'=>SORT_DESC])->one();
        if($topRcd&&$topRcd->user_id == $user_id){
            $status = $strict?'2':'0';
            return Json::error('您在领先位置',$status);
        }

        $num = Yii::$app->request->post('num',0);
        $time = $num>0?$num:1;
        $money = $auction->fee*$time;
        $useData = $user->reduceMoney($money);
        if($user->take_money<0)
            return Json::error('用户拍币不足');
        $user->save(false);
        $order = Saleorder::getOrCreate($auction,$user);
        $order->num+=$time;
        $order->take_money+=$useData['take_money'];
        $order->give_money+=$useData['give_money'];
        $order->save(false);
        if($time == 1){//直接出价
            $model = BidQueue::create($auction,$user);
        }else{//连续出价
            $model = BidSericesqueue::create($auction,$user,$num);
        }
        if($model instanceof BidSericesqueue){
            $data = [
                'bid_num'=>strval($model->initial_num-$model->num),
                'bid_initial_num'=>strval($model->initial_num),
            ];
        }else{
            $data = [
                'bid_num'=>'0',
                'bid_initial_num'=>'0',
            ];
        }
        Bill::log('参与竞拍',-$auction->fee,$user->userid);
        return Json::success($data);
    }
    /**
     * 出价记录
     * @return array
     */
    public function actionRcd()
    {
        $product_id = Request::strictpost('product_id','缺少产品id');
        $auction_id = Yii::$app->request->post('auction_id');

        $first_auction_object = $auction_id?Auction::findOne($auction_id):Auction::getFirst($product_id);
        $query = BidRcd::find()->where(['auction_id'=>$first_auction_object->auctionid]);
        $count = $query->count();
        $pagination = Pagination::get($count);
        $bid_rcds = $query
            ->orderBy(['bidrcdid'=>SORT_DESC])
            ->limit($pagination->limit)
            ->offset($pagination->offset)
            ->all();
        $data = $bid_rcds;
        return Json::success($data);
    }
    /**
     * 历史成交价
     * @return string
     */
    public function actionHistoryjson($product_id)
    {

        $this->html();
        $product_object = Product::findOne($product_id);
        $fields = ['pid','name','type_id','spec'];
        $extraFields = ['first_pic'];
        $product = $product_object->toArray($fields,$extraFields);
        $first_auction = Auction::getFirst($product_id);

        $auction_query = Auction::find()
            ->where(['product_id'=>$product_id,'state'=>Auction::STATE_NOT_AUCTION])
            ->limit(20);

        $auctions = $auction_query->all();
        $avg = floatval($auction_query->average('price'));


        $labels = [];
        $data = [];

        /** @var  $auctions Auction[]*/
        foreach($auctions as $key=>$auction){
            $labels[] = sprintf('%08d',$auction->periods);
            $data[] = $auction->price;
        }
        $labels = json_encode($labels);
        $data = json_encode($data);

        return  $this->render('history',[
            'product'=>$product,
            'first_auction'=>$first_auction,
            'auctions'=>$auctions,
            'data'=>$data,
            'labels'=>$labels,
            'avg'=>$avg
        ]);
    }

    /**
     * 正在热拍
     * @return array
     */
    public function actionIsaucs()
    {
        $user_id = Yii::$app->request->post('user_id',0);
        $query = Auction::find()
            ->where(['state'=>Auction::STATE_IS_AUCTION]);
        $count = $query->count();

        $pagination = Pagination::get($count);

        $objects = $query
            ->orderBy(['product_id'=>SORT_DESC])
            ->indexBy('product_id')
            ->limit($pagination->limit)
            ->offset($pagination->offset)
            ->all();
        $auctions = [];
        /** @var  $object Auction*/
        foreach($objects as $object){
            $auctions[] = Product::getProduct($object->product_id,$user_id,$object);
        }
        $data = [
            'auctions'=>$auctions,
            'auction_count'=>strval($count),
        ];
        return Json::success($data);
    }

    /**
     * 我在拍
     * @return array
     */
    public function actionMyaucs()
    {
        $user_id = Yii::$app->request->post('user_id',0);
        $query = Saleorder::find()->where(['user_id'=>$user_id,'state'=>Saleorder::STEAT_PATTING]);
        $count = $query->count();
        $pagination = Pagination::get($count);
        $objects = $query
            ->orderBy(['product_id'=>SORT_DESC])
            ->indexBy('product_id')
            ->limit($pagination->limit)
            ->offset($pagination->offset)
            ->all();
        $auctions = [];

        /** @var  $objects Saleorder[]*/
        foreach($objects as $object){
            $auctions[] = Product::getProduct($object->product_id,$user_id);
        }

        $data = [
            'auctions'=>$auctions,
            'auction_count'=>strval($count),
        ];
        return Json::success($data);
    }

    /**
     * 我的收藏
     * @return array
     */
    public function actionMycollects(){
        $user_id = Yii::$app->request->post('user_id',0);
        $user = User::findOne($user_id);
        $auctions = [];
        $count = 0;
        if($user){
            $query = $user->getCollects();
            $count = $query->count();
            $pagination = Pagination::get($count);
            /** @var  $objects Product[]*/
            $objects = $query->limit($pagination->limit)->offset($pagination->offset)->all();
            foreach($objects as $object){
                $product = Product::getProduct($object->pid,$user_id);
                if($product){
                    $auctions[] = $product;
                }
            }
        }
        $data = [
            'auctions'=>$auctions,
            'auction_count'=>empty($auctions)?'0':strval($count),
        ];
        return Json::success($data);
    }
    /**
     * 历史成交价
     * @return string
     */
    public function actionHistory()
    {

        $this->html();
        $product_id = Request::strictpost('product_id','缺少产品id');
        $product_object = Product::findOne($product_id);
        $fields = ['pid','name','type_id','spec'];
        $extraFields = ['first_pic'];
        $product = $product_object->toArray($fields,$extraFields);
        $first_auction = Auction::getFirst($product_id);

        $auction_query = Auction::find()
            ->where(['product_id'=>$product_id,'state'=>Auction::STATE_NOT_AUCTION])
            ->limit(20);

        $auctions = $auction_query->all();
        $avg = floatval($auction_query->average('price'));


        $labels = [];
        $data = [];

        /** @var  $auctions Auction[]*/
        foreach($auctions as $key=>$auction){
            $labels[] = sprintf('%08d',$auction->periods);
            $data[] = $auction->price;
        }
        $labels = json_encode($labels);
        $data = json_encode($data);

        return $this->render('history',[
            'product'=>$product,
            'first_auction'=>$first_auction,
            'auctions'=>$auctions,
            'data'=>$data,
            'labels'=>$labels,
            'avg'=>$avg
        ]);
    }
}